/* 
* Copyright (C) 2011-2018 ShenZhen iBOXSaaS Information Technology Co.,Ltd. 
* 
* All right reserved. 
* 
* This software is the confidential and proprietary 
* information of iBOXSaaS Company of China. 
* ("Confidential Information"). You shall not disclose 
* such Confidential Information and shall use it only 
* in accordance with the terms of the contract agreement 
* you entered into with iBOXSaaS inc. 
* 
*/

package com.iboxpay.open.gateway.fallback;

import java.io.ByteArrayInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.nio.charset.Charset;

import org.iboxpay.open.common.constants.ResultEnums;
import org.iboxpay.open.common.vo.BaseResponseVo;
import org.springframework.cloud.netflix.zuul.filters.route.ZuulFallbackProvider;
import org.springframework.http.HttpHeaders;
import org.springframework.http.HttpStatus;
import org.springframework.http.MediaType;
import org.springframework.http.client.ClientHttpResponse;
import org.springframework.stereotype.Component;  
 
/**
 * 
 * ServiceFallbackProvider.java
 * @author xuxiao
 * @date 2018/06/15
 */
@Component  
@lombok.extern.slf4j.Slf4j
public class ServiceFallbackProvider implements ZuulFallbackProvider {  
  
    @Override  
    public String getRoute() {  
        return "*";  
    }  
  
    @Override  
    public ClientHttpResponse fallbackResponse() {  
        return new ClientHttpResponse() {  
            @Override  
            public HttpStatus getStatusCode() throws IOException {  
                return HttpStatus.OK;  
            }  
  
            @Override  
            public int getRawStatusCode() throws IOException {  
                return this.getStatusCode().value();  
            }  
  
            @Override  
            public String getStatusText() throws IOException {  
                return this.getStatusCode().getReasonPhrase();  
            }  
  
            @Override  
            public void close() {  
  
            }  
  
            @Override  
            public InputStream getBody() throws IOException {  
            	log.error("网关超时,路由路径:" + ServiceFallbackProvider.this.getRoute());
            	BaseResponseVo baseResponse = new BaseResponseVo();
            	baseResponse.setResultCode(ResultEnums.routeError.getCode());
            	baseResponse.setErrorDesc(ResultEnums.routeError.getDesc());
                return new ByteArrayInputStream(baseResponse.toString().getBytes()); 
            }  
  
            @Override  
            public HttpHeaders getHeaders() {  
                HttpHeaders headers = new HttpHeaders();  
                MediaType mt = new MediaType("application", "json", Charset.forName("UTF-8"));  
                headers.setContentType(mt);  
                return headers;  
            }  
        };  
    }  
}  